<?php

namespace backend\modules\business\methods\cashier;

use backend\modules\business\methods\base\Basemethod;
use common\models\BusMemberConsumeList;
use common\models\BusTempFinance;
use common\models\BusMember;
use common\models\Status;
use common\models\BusRepertory;
use common\models\BusConfig;
use common\models\BusEmployee;

/**
 * 财务收银(选择商品并修改)
 * @author      miaoyu
 * @date        2016-3-4
 * @version     2.0
 * @copyright   Copyright 2016 meelier.com
 * 收银类型   1：储值卡  2：疗程卡   3：家居产品  4：合作项目  5：服务项目
 */
class Choosegoods extends Basemethod
{
    /**
     * 已选择产品列表
     * @var unknown
     */
    private $productRecord;
    /**
     * 结算总价
     * @var unknown
     */
    private $totalPrice;
    /**
     * 会员账户余额
     * @var unknown
     */
    private $memberBalance;
    /**
     * 会员赠送金额
     * @var unknown
     */
    private $memberGivebalance;
    /**
     * 会员欠款金额
     * @var unknown
     */
    private $debtCount;

    private $consumeId;
    private $date;

    /**
     * 选择产品
     * @date: 2016-3-2
     * @author: futao
     */
    public function chooseProduct()
    {
        $memberId = intval($this->postParam('member_id', 0));
        $relationId = intval($this->postParam('relation_id', 0));
        $financeType = intval($this->postParam('finance_type', 0));
        $consumeName = $this->postParam('consume_name', '');
        $sellPrice = $this->postParam('sell_price', 0);
        $reallyPrice = $this->postParam('really_price', 0);
        $count = $this->postParam('count', 0);
        $giveBalance = $this->postParam('give_balance', 0);
        $totalPrice = $reallyPrice * $count;
        $sessionId = $_COOKIE['PHPSESSID'];
        $shopId = $this->userInfo->shop_id;
        if ($relationId < 1) {
            $this->setError('关联ID不能为空!');
        }
        if ($count < 1) {
            $this->setError('数量不能为空!');
        }
        if ($reallyPrice < 0 || $sellPrice < 0) {
            $this->setError('价格不能为负数!');
        }
        if (!in_array($financeType, [1, 2, 3, 4, 5])) {
            $this->setError('error!');
        }
        $info = BusMember::find()
            ->where("member_id = {$memberId} and shop_id = {$shopId} and del_flag = 1")
            ->asArray()->one();
        if (count($info) < 1) {
            $this->setError('会员ID错误!');
        }
        if ($financeType == 1) {
            $balanceCardcount = BusTempFinance::find()
                ->where("shop_id = :shopId and member_id = :memberId and finance_type = :type and session_id = '{$sessionId}'", [':shopId' => $this->userInfo->shop_id, ':memberId' => $memberId, ':type' => 1])
                ->count();
            if ($balanceCardcount > 0) {
                $this->setError('只能选择一张充值卡!');
            }
            $cardInfo = BusConfig::find()
                ->where("config_id = :id and shop_id = :shop_id and config_type = 1", [':id' => $relationId, ':shop_id' => $this->userInfo->shop_id])
                ->one();
            if (!$cardInfo) {
                $this->setError('充值卡信息错误!');
            }
            //$recharge = $reallyPrice;
            $recharge = $reallyPrice;
            $sellPrice = $cardInfo->config_val;
//            $reallyPrice = $cardInfo->config_val;
            $totalPrice = $reallyPrice * $count;
        }
        $totalCount = BusTempFinance::find()
            ->where("shop_id = :shopId and member_id = :memberId and session_id = '{$sessionId}'", [':shopId' => $this->userInfo->shop_id, ':memberId' => $memberId])
            ->count();
        if ($totalCount > 7) {
            $this->setError('最多选择八件商品!');
        }
        $bustempfinanceModel = new BusTempFinance();
        $bustempfinanceModel->member_id = $memberId;
        $bustempfinanceModel->finance_type = $financeType;
        $bustempfinanceModel->consume_name = $consumeName;
        $bustempfinanceModel->sell_price = $sellPrice;
        $bustempfinanceModel->really_price = $reallyPrice;
        $bustempfinanceModel->count = $count;
        $bustempfinanceModel->relation_id = $relationId;
        $bustempfinanceModel->give_balance = $giveBalance;
        $bustempfinanceModel->total_price = $totalPrice;
        $bustempfinanceModel->session_id = $sessionId;
        $bustempfinanceModel->shop_id = $shopId;
        $bustempfinanceModel->recharge = $recharge;
        if (!$bustempfinanceModel->save(false)) {
            $this->setError('error!');
        } else {
            $this->formatData();
        }
    }

    /**
     * 已选产品列表
     * @date: 2016-3-4
     * @author: futao
     */
    public function productList()
    {
        $memberId = intval($this->postParam('member_id', 0));
        if ($memberId < 1) {
            $this->setError('会员ID错误!');
        }
        $where = $this->where;
        $where[] = 'session_id = :session_id';
        $bind[':session_id'] = $_COOKIE['PHPSESSID'];
        $where[] = 'member_id = :member_id';
        $bind[':member_id'] = $memberId;
        $whereStr = implode(" and ", $where);
        $list = BusTempFinance::find()
            ->where($whereStr, $bind)
            ->orderBy("finance_id desc")
            ->asArray()->all();
        foreach ($list as $k => $v) {
            if ($list[$k]['employee_id'] == '') {
                continue;
            }
            $staffInfo = '';
            $staffInfo = BusEmployee::find()->where('employee_id = :id and shop_id = :shop_id', [':id' => $list[$k]['employee_id'], ':shop_id' => $this->userInfo->shop_id])->one();
            $list[$k]['employee_name'] = $staffInfo->employee_name;
        }
        $this->formatData($list);
    }

    /**
     * 删除已选的产品
     * @date: 2016-3-4
     * @author: futao
     */
    public function delProduct()
    {
        $id = intval($this->postParam('id', 0));
        $memberId = intval($this->postParam('member_id', 0));
        if ($id < 1) {
            $this->setError('ID错误');
        }
        if ($memberId < 1) {
            $this->setError('会员ID错误!');
        }
        $where = $this->where;
        $where[] = 'member_id = :member_id';
        $bind[':member_id'] = $memberId;
        $where[] = 'session_id = :session_id';
        $bind[':session_id'] = $_COOKIE['PHPSESSID'];
        $where[] = 'finance_id = :id';
        $bind[':id'] = $id;
        $whereStr = implode(' and ', $where);
        $info = BusTempFinance::find()
            ->where($whereStr, $bind)
            ->one();
        if (!$info) {
            $this->setError('请求错误！');
        }
        if ($info->delete()) {
            $this->formatData();
        } else {
            $this->setError('删除失败!');
        }
    }

    /**
     * 编辑已选产品 传任意参数修改
     * @date: 2016-3-7
     * @author: futao
     */
    public function updateProduct()
    {
        $id = intval($this->postParam('id', 0));
        $memberId = intval($this->postParam('member_id', 0));
        $financeType = intval($this->postParam('finance_type', 0));
        $consumeName = $this->postParam('consume_name', '');
        //$sellPrice = $this->postParam('sell_price','');
        $reallyPrice = $this->postParam('really_price', 0);
        $count = $this->postParam('count', 0);
        $employeeId = intval($this->postParam('employee_id', 0));
        $reward = $this->postParam('reward', 0);
        if ($id < 1) {
            $this->setError('ID错误');
        }
        if ($memberId < 1) {
            $this->setError('会员ID错误!');
        }
        if ($count < 1 && $this->variableIsexist('count')) {
            $this->setError('数量不能为空!');
        }
        if ($reallyPrice < 0 && $this->variableIsexist('really_price')) {
            $this->setError('价格不能为负数!');
        }
        /* if($sellPrice < 0 && $this->variableIsexist('sell_price')){
            $this->setError('价格不能为负数!');
        } */
        if (!in_array($financeType, [1, 2, 3, 4, 5]) && $this->variableIsexist('finance_type')) {
            $this->setError('error!');
        }
        $where = $this->where;
        $where[] = 'member_id = :member_id';
        $bind[':member_id'] = $memberId;
        $where[] = 'session_id = :session_id';
        $bind[':session_id'] = $_COOKIE['PHPSESSID'];
        $where[] = 'finance_id = :id';
        $bind[':id'] = $id;
        $whereStr = implode(' and ', $where);
        $bustempfinanceModel = BusTempFinance::find()
            ->where($whereStr, $bind)
            ->one();
        if (!$bustempfinanceModel) {
            $this->setError('请求错误!');
        }
        if ($this->variableIsexist('count') && $this->variableIsexist('really_price')) {
            $totalPrice = $reallyPrice * $count;
        }
        if ($this->variableIsexist('count') && $this->variableIsexist('really_price') === false) {
            $totalPrice = $count * $bustempfinanceModel->really_price;
        }
        if ($this->variableIsexist('count') === false && $this->variableIsexist('really_price')) {
            $totalPrice = $bustempfinanceModel->count * $reallyPrice;
        }
        if ($this->variableIsexist('employee_id') && $employeeId > 0) {
            $info = BusEmployee::find()->where('employee_id = :id and shop_id = :shop_id', [':id' => $employeeId, ':shop_id' => $this->userInfo->shop_id])->one();
            if (!$info) {
                $this->setError('员工ID错误!');
            }
        }
        if ($reward != '') {
            if ($reward > $bustempfinanceModel->total_price) {
                $this->setError('销售业绩不能大于总金额！');
            }
        }
        if ($financeType > 0 && $this->variableIsexist('finance_type')) $bustempfinanceModel->finance_type = $financeType;
        if ($consumeName != '' && $this->variableIsexist('consume_name')) $bustempfinanceModel->consume_name = $consumeName;
        //if($sellPrice != '')$bustempfinanceModel->sell_price = $sellPrice;
        if ($reallyPrice > -1 && $this->variableIsexist('really_price')) $bustempfinanceModel->really_price = $reallyPrice;
        if ($count > 0 && $this->variableIsexist('count')) $bustempfinanceModel->count = $count;
        if ($totalPrice != '') $bustempfinanceModel->total_price = $totalPrice;
        if ($employeeId > 0  && $this->variableIsexist('employee_id')) $bustempfinanceModel->employee_id = $employeeId;
        if ($reward != '' && $this->variableIsexist('reward')) $bustempfinanceModel->reward = $reward;
        if (!$bustempfinanceModel->save(false)) {
            $this->setError('修改失败!');
        } else {
            $this->formatData();
        }
    }

    /**
     * 结算界面
     * @date: 2016-3-7
     * @author: futao
     */
    public function clearing()
    {
        $this->setlayout('/alert');
        $this->disableDebugtool();
        $memberId = intval($this->getParam('member_id', 0));
        $shopId = $this->userInfo->shop_id;
        if ($memberId < 1) {
            $this->errorjs('会员ID错误!');
        }
        $memberInfo = BusMember::find()
            ->select([
                'member_balance',
                'member_give_balance'
            ])
            ->where("member_id = {$memberId} and shop_id = {$shopId} and del_flag = 1")
            ->asArray()->one();
        if (count($memberInfo) < 1) {
            $this->errorjs('会员ID错误!');
        }
        $where = $this->where;
        $where[] = 'member_id = :member_id';
        $bind[':member_id'] = $memberId;
        $where[] = 'session_id = :session_id';
        $bind[':session_id'] = $_COOKIE['PHPSESSID'];
        $whereStr = implode(' and ', $where);
        $count = BusTempFinance::find()
            ->where($whereStr, $bind)
            ->count();
        if ($count < 1) {
            $this->errorjs('未选择商品!');
        }
        $totalPrice = BusTempFinance::find()
            ->select([
                'sum(total_price) as pay_price',
            ])
            ->where($whereStr, $bind)
            ->asArray()->all();
        //充值卡总金额
        $totalPricebalance = BusTempFinance::find()
            ->select([
                'sum(total_price) as pay_price',
            ])
            ->where($whereStr . ' and finance_type = 1', $bind)
            ->asArray()->all();
        //疗程卡总金额
        $totalPricehealth = BusTempFinance::find()
            ->select([
                'sum(total_price) as pay_price',
            ])
            ->where($whereStr . ' and finance_type = 2', $bind)
            ->asArray()->all();
        //家居产品总金额
        $totalPriceproduct = BusTempFinance::find()
            ->select([
                'sum(total_price) as pay_price',
            ])
            ->where($whereStr . ' and finance_type = 3', $bind)
            ->asArray()->all();
        //合作项目总金额
        $totalPriceprojects = BusTempFinance::find()
            ->select([
                'sum(total_price) as pay_price',
            ])
            ->where($whereStr . ' and finance_type = 4', $bind)
            ->asArray()->all();
        //服务项目总金额
        $totalPriceservice = BusTempFinance::find()
            ->select([
                'sum(total_price) as pay_price',
            ])
            ->where($whereStr . ' and finance_type = 5', $bind)
            ->asArray()->all();
        $totalPricebalance = $totalPricebalance[0]['pay_price'] ? $totalPricebalance[0]['pay_price'] : 0;//充值卡总金额
        $totalPricehealth = $totalPricehealth[0]['pay_price'] ? $totalPricehealth[0]['pay_price'] : 0;//疗程卡总金额
        $totalPriceproduct = $totalPriceproduct[0]['pay_price'] ? $totalPriceproduct[0]['pay_price'] : 0;//家居产品总金额
        $totalPriceprojects = $totalPriceprojects[0]['pay_price'] ? $totalPriceprojects[0]['pay_price'] : 0;//合作项目总金额
        $totalPriceservice = $totalPriceservice[0]['pay_price'] ? $totalPriceservice[0]['pay_price'] : 0;//服务项目总金额
        $totalPrice = $totalPrice[0]['pay_price'] ? $totalPrice[0]['pay_price'] : 0;//全部总金额
        $info = [
            'member_balance' => $memberInfo['member_balance'],
            'member_give_balance' => $memberInfo['member_give_balance'],
            'totalPricebalance' => $totalPricebalance,
            'totalPricehealth' => $totalPricehealth,
            'totalPriceproduct' => $totalPriceproduct,
            'totalPriceprojects' => $totalPriceprojects,
            'totalPriceservice' => $totalPriceservice,
            'totalPrice' => $totalPrice,
            'memberId' => $memberId
        ];
        return $this->render('clearing', ['info' => $info]);
    }

    /**
     * 获取用户信息JSON返回
     * @date: 2016-2-29
     * @author: futao
     */
    public function getUserinfo()
    {
        $id = intval($this->postParam('id', 0));
        if ($id < 1) {
            $this->setError('ID错误!');
        }
        $where = $this->where;
        $where[] = 'member_id = ' . $id;
        $where[] = 'del_flag = ' . Status::NORMAL;
        $whereStr = implode(' and ', $where);
        $info = BusMember::find()->where($whereStr)->asArray()->one();
        if (count($info > 0)) {
            \Yii::$app->session->set('member_id', $id);
            $this->formatData($info);
        } else {
            $this->setError('失败!');
        }
    }

    /**
     * 结算操作
     * @date: 2016-3-7
     * @author: futao
     */
    public function clearingAction()
    {
        $balancePay = $this->postParam('balance_pay', 0);
        $giveBalancepay = $this->postParam('give_balance_pay', 0);
        $memberId = intval($this->postParam('member_id', 0));
        $cashPay = $this->postParam('cash_pay', 0);
        $unionPay = $this->postParam('union_pay', 0);
        $date = $this->postParam('date',date('Y-m-d H:i:s'));
        $this->date = $date;
        $shopId = $this->userInfo->shop_id;
        if ($balancePay < 0 || $giveBalancepay < 0 || $memberId < 0 || $cashPay < 0 || $unionPay < 0) {
            $this->errorjs('参数错误!');
        }
        $memberInfo = BusMember::find()
            ->select([
                'member_balance',
                'member_give_balance',
                'member_debt'
            ])
            ->where("member_id = {$memberId} and shop_id = {$shopId} and del_flag = 1")
            ->asArray()->one();
        if (count($memberInfo) < 1) {
            $this->errorjs('会员ID错误!');
        }
        $this->memberBalance = $memberInfo['member_balance'];
        $this->memberGivebalance = $memberInfo['member_give_balance'];
        $this->debtCount = $memberInfo['debt_count'];
        $where = $this->where;
        $where[] = 'member_id = :member_id';
        $bind[':member_id'] = $memberId;
        $where[] = 'session_id = :session_id';
        $bind[':session_id'] = $_COOKIE['PHPSESSID'];
        $whereStr = implode(' and ', $where);
        $this->productRecord = BusTempFinance::find()
            ->where($whereStr, $bind)
            ->asArray()->all();
        if (count($this->productRecord) < 1) {
            $this->errorjs('未选择商品!');
        }
        $transaction = \Yii::$app->db->beginTransaction();
        try {//顺序不能改变
            $this->homeProducthandle();//家居产品处理
            $this->healthCardhandle();//疗程卡处理
            $this->serviceProjecthandle();//服务项目处理
            $this->cooperationProjecthandle();//合作项目处理
            $this->balanceCardhandle();//充值卡处理
            $this->staffHandle();//员工处理
            $return_consume_id = $this->memberHandle($balancePay, $giveBalancepay, $cashPay, $unionPay);//会员处理
            $this->add_member_consume_list($return_consume_id, $this->date);// 添加消费详细记录列表
            $this->unsetRecord();//删除临时表数据
            $transaction->commit();
            $this->errorjs('结算成功!', 1);
        } catch (\Exception $e) {
            $transaction->rollBack();
            $this->errorjs($e->getMessage());
            //echo $e->getMessage(),$e->getLine();
        }
    }

    /**
     * 家居产品处理(扣库存)
     * @date: 2016-3-10
     * @author: futao
     * 收银类型   1：储值卡  2：疗程卡   3：家居产品  4：合作项目  5：服务项目
     */
    private function homeProducthandle()
    {
        $list = $this->selectRecord(3);
        if ($list == '') {
            return;
        }
        $repertoryModel = new BusRepertory();
        foreach ($list as $val) {
            $repertoryId = $val['relation_id'];
            $this->totalPrice += $val['really_price'] * $val['count'];
            if ($repertoryModel->updateRepertorycount($repertoryId, $val['count'], $this->userInfo->shop_id, $this->userInfo->boss_uid, $this->userInfo->uid) === false) {
                throw new \Exception($repertoryModel->getErrormessage());
            }
        }
        return true;
    }

    /**
     * 充值卡处理
     * @date: 2016-3-10
     * @author: futao
     */
    private function balanceCardhandle()
    {
        $list = $this->selectRecord(1);
        if ($list == '') {
            return;
        }
        $list = $list[0];
        $this->totalPrice += $list['really_price'] * $list['count'];
        $memberInfo = BusMember::find()
            ->where("shop_id = :shop_id and member_id = :member_id", [':shop_id' => $this->userInfo->shop_id, ':member_id' => $list['member_id']])
            ->one();
        $memberBalance = $memberInfo->member_balance + $list['recharge'] * $list['count'];
        $memberGivebalance = $memberInfo->member_give_balance + $list['give_balance'] * $list['count'];
        $memberGrade = $list['consume_name'];
        $data['member_grade'] = $memberGrade;
        $data['member_balance'] = $memberBalance;
        $data['member_give_balance'] = $memberGivebalance;
        $this->memberBalance = $memberBalance;
        $this->memberGivebalance = $memberGivebalance;
        $memberModel = new BusMember();
        if ($memberModel->updateMemberinfo($list['member_id'], $data) === false) {
            throw new \Exception($memberModel->errorMessage);
        }
        unset($data);
        if($list['recharge'] > 0){
        	$data['member_balance'] = $memberBalance;
        	$data['type'] = '储值卡';
        	$data['account_type'] = 1;
        	$data['account_money'] = $list['recharge'] * $list['count'];
        	$memberModel->memberBalancelog($list['member_id'], $data);
        }
        unset($data);
        if($list['give_balance'] > 0){
	        $data['member_give_balance'] = $memberGivebalance;
	        $data['type'] = '赠送金';
	        $data['account_type'] = 1;
	        $data['account_money'] = $list['give_balance'] * $list['count'];
	        $memberModel->memberBalancelog($list['member_id'], $data);
        }
        return true;
    }

    /**
     * 疗程卡处理
     * @date: 2016-3-10
     * @author: futao
     */
    private function healthCardhandle()
    {
        $list = $this->selectRecord(2);
        if ($list == '') {
            return;
        }
        foreach ($list as $val) {
            $cardId = $val['relation_id'];
            $this->totalPrice += $val['really_price'] * $val['count'];
            $isGive = 0;
            if ($val['really_price'] < 1) {
                $isGive = 1;
            }
            $cardInfo = BusConfig::find()
                ->where("config_type = :type and shop_id = :shop_id and config_id = {$cardId}", [':type' => 2, ':shop_id' => $this->userInfo->shop_id])
                ->one();
            if (!$cardInfo) {
                throw new \Exception('疗程卡数据错误!');
            }
            $memberModel = new BusMember();
            $data['card_name'] = $val['consume_name'];
            $data['total_times'] = $cardInfo->config_val * $val['count'];
            $data['remain_times'] = $cardInfo->config_val * $val['count'];
            $data['create_time'] = date("Y-m-d H:i:s", time());
            $data['member_id'] = $val['member_id'];
            $data['is_give'] = $isGive;
            $data['total_price'] = $val['really_price'] * $val['count'];
            $data['shop_id'] = $this->userInfo->shop_id;
            $data['boss_id'] = $this->userInfo->boss_uid;
            if (!$memberModel->addMemberbeautycard($data)) {
                throw new \Exception($memberModel->errorMessage);
            }
        }
        return true;
    }

    /**
     * 员工处理
     * @date: 2016-3-10
     * @author: futao
     */
    private function staffHandle()
    {
        $list = $this->productRecord;
        foreach ($list as $val) {
            $employeeId = $val['employee_id'];
            if ($employeeId == '' || $val['reward'] == '') {
                continue;
            }
            $employeeModel = new BusEmployee();
            unset($data);
            $data['employee_id'] = $employeeId;
            if ($val['finance_type'] == 4) {
                $data['epiboly_reward'] = $val['reward'];
            } else {
                $data['sell_reward'] = $val['reward'];
            }
            if (!$employeeModel->addEmployeereward($this->userInfo->shop_id, $this->userInfo->boss_uid, $data)) {
                throw new \Exception($employeeModel->getError());
            }
        }
        return true;
    }

    /**
     * 会员处理（记录会员消费记录）
     * @date: 2016-3-10
     * @author: futao
     */
    private function memberHandle($balancePay, $giveBalancepay, $cashPay, $unionPay)
    {
        $list = $this->productRecord;
        foreach ($list as $k => $val) {
            if ($k == 0) {
                $goodsName = $this->getConsumeName($val);
                $consumptionType = $this->consumptionType($val['finance_type']);
            } else {
                $goodsName = $goodsName . ',' . $this->getConsumeName($val);//消费名称
                $consumptionType = $consumptionType . ',' . $this->consumptionType($val['finance_type']);//消费类型
            }
            if (!isset($memberId)) $memberId = $val['member_id'];
        }
        $memberModel = new BusMember();
        //欠款记录
        if (($balancePay + $giveBalancepay + $cashPay + $unionPay) < $this->totalPrice) {
            $debtPrice = $this->totalPrice - ($balancePay + $giveBalancepay + $cashPay + $unionPay);
            $memberInfo = BusMember::find()->where("shop_id = :shop_id and member_id = :member_id", [':shop_id' => $this->userInfo->shop_id, ':member_id' => $memberId])->one();
            if (!$memberInfo) {
                throw new \Exception('会员信息错误!');
            }
            $debtData['member_id'] = $memberId;
            $debtData['debt_time'] = $this->date;
            $debtData['total_count'] = $this->totalPrice;
            $debtData['already_paid'] = $balancePay + $giveBalancepay + $cashPay + $unionPay;
            $debtData['debt_count'] = $debtPrice;
            $debtData['debt_name'] = $goodsName;
            $debtData['member_name'] = $memberInfo->member_name;
            $debtData['debt_state'] = 0;
            $debtData['shop_id'] = $this->userInfo->shop_id;
            $debtData['boss_id'] = $this->userInfo->boss_uid;
            if (!$memberModel->addMemberdebt($debtData)) {
                throw new \Exception($memberModel->errorMessage);
            }
            $memberData['member_balance'] = $memberInfo->member_balance;
            $memberData['member_give_balance'] = $memberInfo->member_give_balance;
            $memberData['member_debt'] = $memberInfo->member_debt + ($this->debtCount + ($this->totalPrice - ($balancePay + $giveBalancepay + $cashPay + $unionPay)));
            if ($memberModel->updateMemberinfo($memberId, $memberData) === false) {
                throw new \Exception($memberModel->errorMessage);
            }
            unset($data);
            $data['member_debt'] = $memberData['member_debt'];
            $data['type'] = '欠款';
            $data['account_type'] = 1;
            $data['account_money'] = $this->debtCount + ($this->totalPrice - ($balancePay + $giveBalancepay + $cashPay + $unionPay));
            $memberModel->memberBalancelog($memberId, $data);
        }
        unset($data);
        //记录消费记录
        $data['consume_amount'] = $this->totalPrice;
        $data['consume_name'] = $goodsName;
        $data['consume_type'] = $consumptionType;
        $data['cash_pay'] = $cashPay ? $cashPay : 0;
        $data['unionpay'] = $unionPay ? $unionPay : 0;
        $data['balance_pay'] = $balancePay ? $balancePay : 0;
        $data['give_pay'] = $giveBalancepay ? $giveBalancepay : 0;
        $data['debt_count'] = $debtPrice ? $debtPrice : 0;
        $data['boss_id'] = $this->userInfo->boss_uid;
        $data['shop_id'] = $this->userInfo->shop_id;
        $data['last_consume_time'] = $this->date;
        $data['consume_time'] = $this->date;
        $return_id = $memberModel->addMemberconsume($memberId, $data);
        if (!$return_id) {
            throw new \Exception($memberModel->errorMessage);
        }
        //扣会员储值卡和赠送金额
        if($balancePay > 0 || $giveBalancepay > 0){
	        if($balancePay!='')$balanceData['member_balance'] = $this->memberBalance - $balancePay;
	        if($giveBalancepay!='')$balanceData['member_give_balance'] = $this->memberGivebalance - $giveBalancepay;
	        if ($memberModel->updateMemberinfo($memberId, $balanceData) === false) {
	            throw new \Exception($memberModel->errorMessage);
	        }
	        unset($data);
	        if($balancePay > 0){
	        	$data['member_balance'] = $balanceData['member_balance'];
	        	$data['type'] = '储值卡';
	        	$data['account_type'] = 2;
	        	$data['account_money'] = $balancePay;
	        	$memberModel->memberBalancelog($memberId, $data);
	        }
	        unset($data);
	        if($giveBalancepay > 0){
	        	$data['member_give_balance'] = $balanceData['member_give_balance'];
	        	$data['type'] = '赠送金';
	        	$data['account_type'] = 2;
	        	$data['account_money'] = $giveBalancepay;
	        	$memberModel->memberBalancelog($memberId, $data);
	        }
        }
        
        return $return_id;
    }

    /**
     * 服务项目处理
     * @date: 2016-3-10
     * @author: futao
     */
    private function serviceProjecthandle()
    {
        $list = $this->selectRecord(5);
        if ($list == '') {
            return;
        }
        foreach ($list as $val) {
            $this->totalPrice += $val['really_price'] * $val['count'];
            $isGive = 0;
            if ($val['really_price'] < 1) {
                $isGive = 1;
            }
            $memberModel = new BusMember();
            $data['card_name'] = $val['consume_name'];
            $data['total_times'] = 1*$val['count'];
            $data['remain_times'] = 1*$val['count'];
            $data['create_time'] = date("Y-m-d H:i:s", time());
            $data['member_id'] = $val['member_id'];
            $data['total_price'] = $val['really_price']*$val['count'];
            $data['is_give'] = $isGive;
            $data['shop_id'] = $this->userInfo->shop_id;
            $data['boss_id'] = $this->userInfo->boss_uid;
            if (!$memberModel->addMemberbeautycard($data)) {
                throw new \Exception($memberModel->errorMessage);
            }
        }
        return true;
    }

    /**
     * 合作项目处理
     * @date: 2016-3-10
     * @author: futao
     */
    private function cooperationProjecthandle()
    {
        $list = $this->selectRecord(4);
        if ($list == '') {
            return;
        }
        foreach ($list as $val) {
            $this->totalPrice += $val['really_price'] * $val['count'];
        }
    }

    /**
     * 删除临时表数据
     * @date: 2016-3-11
     * @author: futao
     */
    private function unsetRecord()
    {
        $list = $this->productRecord;
        foreach ($list as $k => $val) {
            if ($k == 0) {
                $ids = $val['finance_id'];
            } else {
                $ids .= ',' . $val['finance_id'];
            }
        }
        if (!BusTempFinance::deleteAll("finance_id in ({$ids})")) {
            throw new \Exception('收银失败!');
        }
        return true;
    }

    /**
     * 增加消费详细记录表
     */
    public function add_member_consume_list($return_consume_id,$date)
    {
        $val = $this->productRecord;
        for ($i = 0; $i < count($val); $i++) {
            $modelMemberConsumeList = new BusMemberConsumeList();
            $modelMemberConsumeList->consume_id = $return_consume_id;
            $modelMemberConsumeList->member_id = $val[$i]['member_id'];
            $modelMemberConsumeList->shop_id = $val[$i]['shop_id'];
            $modelMemberConsumeList->finance_type = $val[$i]['finance_type'];
            $modelMemberConsumeList->consume_name = $val[$i]['consume_name'];
            $modelMemberConsumeList->sell_price = $val[$i]['sell_price'];
            $modelMemberConsumeList->really_price = $val[$i]['really_price'];
            $modelMemberConsumeList->count = $val[$i]['count'];
            $modelMemberConsumeList->total_price = $val[$i]['total_price'];
            $modelMemberConsumeList->employee_id = $val[$i]['employee_id'];
            $modelMemberConsumeList->reward = $val[$i]['reward'];
            $modelMemberConsumeList->session_id = $val[$i]['session_id'];
            $modelMemberConsumeList->create_time = $date;
            $modelMemberConsumeList->give_balance = $val[$i]['give_balance'];
            $modelMemberConsumeList->relation_id = $val[$i]['relation_id'];
            $modelMemberConsumeList->recharge = $val[$i]['recharge'];
            $modelMemberConsumeList->save();
        }
        return true;
    }

    /**
     * 根据类型获取选择产品的记录
     * @date: 2016-3-10
     * @author: futao
     */
    private function selectRecord($type)
    {
        $list = $this->productRecord;
        foreach ($list as $val) {
            if ($val['finance_type'] == $type) {
                $array[] = $val;
            }
        }
        return $array;
    }

    /**
     * 根据数字返回消费类型
     * @date: 2016-3-11
     * @author: futao
     *  收银类型   1：储值卡  2：疗程卡   3：家居产品  4：合作项目  5：服务项目
     */
    private function consumptionType($type)
    {
        switch ($type) {
            case 1:
                return '储值卡';
                break;
            case 2:
                return '疗程卡';
                break;
            case 3:
                return '家居产品';
                break;
            case 4:
                return '合作项目';
                break;
            case 5:
                return '服务项目';
                break;
        }
    }
    /**
     * 拼接消费名称
     * @date: 2016-3-21 
     * @author: futao
     */
    private function getConsumeName($data)
    {
    	if($data['finance_type'] == 2){
    		if($data['relation_id']==''){
    			return $data['consume_name'];
    		}
    		$info = BusConfig::find()
    		->where("config_id = ".$data['relation_id'])
    		->one();
    		if(!$info){
    			return $data['consume_name'];
    		}
    		return $info->config_key.'('.$info->config_val.'次)';
    	}elseif($data['finance_type'] == 3){
    		if($data['relation_id']==''){
    			return $data['consume_name'];
    		}
    		$info = BusRepertory::find()
    		->where("repertory_id = ".$data['relation_id'])
    		->one();
    		if(!$info){
    			return $data['consume_name'];
    		}
    		return $info->repertory_name.$info->repertory_specs.'('.$data['count'].')';
    	}else{
    		return $data['consume_name'];
    	}
    }
}
?>